package org.example.linkedList;

import java.util.Arrays;

/**
 * @Auther: wangbw @Date:2020/12/11 @Description: org.example.linkedList @version: 1.0
 */
public class SquareSort {
    public static void main(String[] args) {
        int[] arr = new int[]{4, 5, 3, 2, 8};
        bubbleSort(arr);
        print(arr);
        int[] arr1 = new int[]{4, 5, 3, 2, 8};
        insertionSort(arr1);
        print(arr1);
        int[] arr2 = new int[]{4, 5, 3, 2, 8};
        selectionSort(arr2);
        print(arr2);
    }

    /*选择*/
    private static void selectionSort(int[] arr) {
        if (isAlreadySort(arr)) return;
        for (int i = 0; i < arr.length - 1; i++) {
            int k = i;
            for (int j = k + 1; j < arr.length; j++) if (arr[j] < arr[k]) k = j;
            if (k != i) {
                int temp = arr[i];
                arr[i] = arr[k];
                arr[k] = temp;
            }
        }
    }

    /*插入*/
    private static void insertionSort(int[] arr) {
        if (isAlreadySort(arr)) return;
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j = i - 1;
            for (; j >= 0; j--)
                if (arr[j] > temp) arr[j + 1] = arr[j];
                else break;
            arr[j + 1] = temp;
        }
    }

    /*冒泡*/
    private static void bubbleSort(int[] arr) {
        if (isAlreadySort(arr)) return;
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < arr.length - i - 1; j++)
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            if (!flag) break;
        }
    }

    private static boolean isAlreadySort(int[] arr) {
        return arr == null || arr.length <= 1;
    }

    private static void print(int[] arr) {
        System.out.println("result:" + Arrays.toString(arr));
    }
}
